/// <reference types="node" />
import { ArchiverError, EntryData } from 'archiver'

const fs = require('fs')
const path = require('path')
const archiver = require('archiver')

/**
 * zip folder
 * sourceFolder 待压缩的文件夹
 * destZip 压缩后的zip文件
 * cb 回调函数
 * includeParent 是否需要包一层
 */
export function zipFolder(sourceFolder: string, destZip: string, cb?: Function, includeParent = false): void {
  // init
  const output = fs.createWriteStream(destZip)
  const archive = archiver('zip', {
    zlib: { level: 9 },
  })

  // on
  output.on('close', function () {
    cb && cb('zip folder success!')
  })
  archive.on('error', function (err: ArchiverError) {
    cb && cb(err)
  })

  // zip
  archive.pipe(output)
  archive.directory(sourceFolder, includeParent ? sourceFolder.substr(path.dirname(sourceFolder).length + 1) : false)

  archive.finalize().then()
}

/**
 * zip file
 * sourceFile 待压缩的文件
 * destZip 压缩后的zip文件
 * cb callback
 */
export function zipFile(sourceFile: string, destZip: string, cb?: Function) {
  // init
  const output = fs.createWriteStream(destZip)
  const archive = archiver('zip', {
    zlib: { level: 9 },
  })

  // on
  output.on('close', function () {
    cb && cb('zip file success!')
  })
  archive.on('error', function (err: ArchiverError) {
    cb && cb(err)
  })

  // zip
  archive.pipe(output)
  archive.file(sourceFile, {
    name: path.basename(sourceFile),
  } as EntryData)

  archive.finalize().then()
}
